﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.RM.Bll;
using CIT.WMS.Product.Bll;

namespace CIT.WMS.RM
{
    public partial class FrmRMOut : Form
    {
        public FrmRMOut()
        {
            InitializeComponent();
        }

        DataTable DtRMOut;
        string DetailNo = string.Empty;
        string realLocationSN = string.Empty;

        string BillNo = "";
        int rowNo = 0;

        string productNumber = string.Empty;  //料号
        string CustomerSN = string.Empty;//供应商
        DateTime? ExpiryDate = null;//有效时间
        string dataCode = string.Empty;
        decimal Qty = 0;
        string lotNo = string.Empty;//批次
        string factory = string.Empty;//生产厂商
        string factortPartNumber = string.Empty;//厂商料号
        string Ext1 = string.Empty;
        bool isRowFinish = false;

        public void clearall()
        {
            DtRMOut.Clear();
            rowNo = 0;
            DetailNo = string.Empty;
            realLocationSN = string.Empty;
            lblRow.Text = "";
            productNumber = string.Empty;  //料号
            CustomerSN = string.Empty;//供应商
            ExpiryDate = null;//有效时间
            dataCode = string.Empty;
            Qty = Convert.ToDecimal(0);
            lotNo = string.Empty;//批次
            factory = string.Empty;//生产厂商
            factortPartNumber = string.Empty;//厂商料号
            Ext1 = string.Empty;
            isRowFinish = false;
        }

        private void txtSN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                try
                {
                    realLocationSN = "";
                    if (txtSN.Text.Contains("#"))
                    {
                        realLocationSN = txtSN.Text;
                    }


                    var arry = realLocationSN.Split('#');
                    if (arry.Count() < 3)
                    {
                        MessageBox.Show("输入的库位格式不正确，请重新输入！");
                        txtSN.Text = "";
                        txtSN.Focus();
                        return;
                    }
                    txtSN.Text = arry[1] + arry[2];

                    var status = Bll_ProductOut.GetLocationSNStatusInInventory(realLocationSN, productNumber);
                    if (status == 0)
                    {
                        var str = txtSN.Text + "库存不足，选择其他库位！";
                        MessageBox.Show(str);
                        txtSN.Text = "";
                        txtSN.Focus();
                        return;
                    }
                    //MessageBoxButtons messButton = MessageBoxButtons.OKCancel;

                    //DialogResult dr = MessageBox.Show("库位[" + realLocationSN + "]，是否确认？", "出库确认", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

                    //if (dr == DialogResult.Cancel)
                    //{
                    //    return;
                    //}
                    txtBoxCode.Focus();
                }
                catch
                {
                    txtBillNo.Focus();
                    txtBillNo.Text = "";
                    txtBoxCode.Text = "";
                    lab_StorageSN.Text = "";
                    txtNum.Text = "";
                    txtSN.Text = "";
                    BillNo = "";
                    rowNo = 0;
                    clearall();
                }
            }
        }

        private void FrmRMOut_Load(object sender, EventArgs e)
        {
            txtBillNo.Focus();
        }

        public void BillNoChange()
        {
            try
            {
                lab_msg.Text = "";

                var txtbillnoList = txtBillNo.Text.Split('-');
                if (txtbillnoList.Length >= 2)
                {
                    BillNo = txtbillnoList[0];
                    rowNo = Convert.ToInt32(txtbillnoList[1]);

                }
                else
                {
                    MessageBox.Show("请选择正确的单号!");
                    txtBillNo.Text = "";
                    return;
                }
                DtRMOut = Bll_RMOut.GetOutRow(BillNo, rowNo);

                decimal realQty = 0;

                if (DtRMOut != null && DtRMOut.Rows.Count > 0)
                {
                    productNumber = DtRMOut.Rows[0]["PartNumber"].ToString();
                    realQty = Convert.ToDecimal(DtRMOut.Rows[0]["RealQty"]);
                    lab_StorageSN.Text = DtRMOut.Rows[0]["Storage_SN"].ToString();
                    Ext1 = DtRMOut.Rows[0]["Ext1"].ToString();
                }
                else
                {
                    MessageBox.Show("请选择正确的单号!");
                    txtBillNo.Text = "";
                    lblRow.Text = "";
                    return;
                }

                lab_msg.Text = txtBillNo.Text + "当前料号:" + productNumber + GetBillInfoMsg(BillNo);
                if (!isRowFinish)
                {

                    var dt = Bll_RMOut.GetRecommendLocationSN(Utils.uContext.CompanyNamek__BackingField, lab_StorageSN.Text, BillNo, productNumber, DtRMOut.Rows[0]["Ext3"].ToString());
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        var dr = dt.Rows[0];
                        var recomLocationSN = dr["Location_SN"].ToString();
                        try
                        {
                            lblRow.Text = recomLocationSN.Split('#')[1] + recomLocationSN.Split('#')[2] + ":" + dr["Qty"].ToString();
                        }
                        catch (Exception ex)
                        {
                            lblRow.Text = dr["Storage_SN"].ToString();
                        }

                        txtSN.Focus();
                    }
                    else
                    {
                        MessageBox.Show("库存不足，无法推荐!");
                        txtBillNo.Text = "";
                        lab_StorageSN.Text = "";
                        lblRow.Text = "";
                        txtBillNo.Focus();
                    }
                }
                else
                {
                    //MessageBox.Show("该订单行数量已满，请选择其他订单行!");
                    txtBillNo.Text = "";
                    lab_StorageSN.Text = "";
                    lblRow.Text = "";
                    txtBillNo.Focus();
                }

            }
            catch
            {
                txtBillNo.Text = "";
                lab_StorageSN.Text = "";
                txtBillNo.Focus();
            }
        }

        private void txtBillNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                BillNoChange();
            }
        }


        private void txtNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13)
            {
                return;
            }
            try
            {
                if (string.IsNullOrEmpty(txtBillNo.Text))
                {
                    MessageBox.Show("请选择单号!");
                    txtBillNo.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(txtSN.Text))
                {
                    MessageBox.Show("请选择库位!");
                    return;
                }
                if (string.IsNullOrEmpty(txtBoxCode.Text))
                {
                    MessageBox.Show("请选择条码!");
                    return;
                }
                if (string.IsNullOrEmpty(txtNum.Text))
                {
                    MessageBox.Show("数量不能未空!");
                    return;
                }

                var dtInver = Bll_ProductIn.GetInventoryInfo(realLocationSN, productNumber);
                decimal locationSNQ = 0;
                string extInver = string.Empty;
                if (dtInver != null && dtInver.Rows.Count > 0)
                {
                    locationSNQ = Convert.ToDecimal(dtInver.Rows[0]["Qty"]);
                    extInver = dtInver.Rows[0]["Ext1"].ToString();
                }
                else
                {
                    var str = txtSN.Text + "库存不足，请选择其他推荐库位！";
                    MessageBox.Show(str);

                    txtSN.Text = "";
                    txtSN.Focus();
                    return;
                }
                var qty = Convert.ToDecimal(txtNum.Text);

                if (qty == 0)
                {
                    MessageBox.Show("出库成品数不能为0或者为空!");
                    return;
                }
                if (qty > locationSNQ)
                {
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;

                    DialogResult dr = MessageBox.Show("库存不足，当前库存[" + locationSNQ + "]，是否确认出库数量为当前库存数量？", "出库确认", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

                    if (dr == DialogResult.Cancel)
                    {
                        return;
                    }
                    else
                    {
                        qty = locationSNQ;
                        txtNum.Text = qty.ToString();
                    }
                }
                bool isPD = false;
                if (string.IsNullOrEmpty(extInver) || extInver.Length != 8)
                {
                    isPD = true;
                }
                else
                {
                    try
                    {
                        DateTime ditetimeExt = Convert.ToDateTime(extInver.Substring(0, 4) + "-" + extInver.Substring(4, 2) + "-" + extInver.Substring(6, 2));
                        if (ditetimeExt >= DateTime.Now)
                        {
                            isPD = false;
                        }
                    }
                    catch
                    {
                        MessageBox.Show("该库位有效期不是正确的日期格式!");
                        return;
                    }
                }
                if (isPD)
                {
                    var dtLiftTime = Bll_RMOut.GetExpriTime(productNumber, realLocationSN);
                    if (!(dtLiftTime != null && dtLiftTime.Rows.Count > 0))
                    {
                        //MessageBoxButtons messButtons = MessageBoxButtons.OKCancel;

                        //DialogResult drs = MessageBox.Show("该物料有效期已过，无法出库!!是否强制出库!", "出库确认", messButtons, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

                        //if (drs == DialogResult.Cancel)
                        //{
                        //    //MessageBox.Show("该物料有效期已过，无法出库!!");
                        //    return;
                        //}
                        MessageBox.Show("该物料有效期已过，无法出库!!");
                        return;
                    }
                }

                if (Qty != qty)
                {
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;

                    DialogResult dr = MessageBox.Show("条码数量:" + Qty + "与实际出库数量" + qty + "不一致，是否确认？", "出库确认", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

                    if (dr == DialogResult.Cancel)
                    {
                        return;
                    }
                }

                if (txtSN.Text != lblRow.Text)
                {
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;

                    DialogResult dr = MessageBox.Show("出库单库位:" + txtSN.Text + "与推荐库位" + lblRow.Text + "不一致，是否确认？", "出库确认", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

                    if (dr == DialogResult.Cancel)
                    {
                        return;
                    }
                }

                //bool isTrue = Bll_RMOut.RMOutStock(BillNo, "", qty, realLocationSN, productNumber, dataCode, lotNo, CustomerSN, Convert.ToDateTime(ExpiryDate), txtBoxCode.Text, Ext1, rowNo.ToString());
                bool isTrue = Utils.NMS.sqlDBService.RMOutStock(BillNo, "", qty, realLocationSN, productNumber, dataCode, lotNo, CustomerSN, Convert.ToDateTime(ExpiryDate), txtBoxCode.Text, Ext1, rowNo.ToString(), Utils.uContext.UserNamek__BackingField);
                if (isTrue)
                {
                    lab_msg.Text = txtBillNo.Text + "出库成功！\r\n" + "当前料号:" + productNumber + GetBillInfoMsg(BillNo);
                    bool tjover = true;
                    var dt = Bll_RMOut.GetRecommendLocationSN(Utils.uContext.CompanyNamek__BackingField, lab_StorageSN.Text, BillNo, productNumber, DtRMOut.Rows[0]["Ext3"].ToString());
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        var dr = dt.Rows[0];
                        var recomLocationSN = dr["Location_SN"].ToString();
                        try
                        {
                            //lblRow.Text = recomLocationSN.Split('#')[1] + recomLocationSN.Split('#')[2];
                            lblRow.Text = recomLocationSN.Split('#')[1] + recomLocationSN.Split('#')[2] + ":" + dr["Qty"].ToString();
                        }
                        catch (Exception ex)
                        {
                            lblRow.Text = dr["Storage_SN"].ToString();
                        }
                    }
                    else
                    {
                        MessageBox.Show("库存不足，无法推荐!");
                        txtBillNo.Text = "";
                        lab_StorageSN.Text = "";
                        lblRow.Text = "";
                        txtBillNo.Focus();
                        tjover = false;
                    }

                    if (isRowFinish)
                    {
                        txtBillNo.Focus();
                        txtBillNo.Text = "";
                        txtBoxCode.Text = "";
                        lab_StorageSN.Text = "";
                        lblRow.Text = "";
                        txtNum.Text = "";
                        txtSN.Text = "";
                        clearall();
                    }
                    else
                    {
                        if (tjover)
                        {
                            txtBoxCode.Focus();
                        }
                        txtBoxCode.Text = "";
                        txtNum.Text = "";
                    }

                }
                else
                {
                    MessageBox.Show(txtBillNo.Text + "出库失败，请检查订单信息与库位信息是否一致,或此库位是否有足够的成品！");
                    txtBillNo.Focus();
                    txtBillNo.Text = "";
                    txtBoxCode.Text = "";
                    lab_StorageSN.Text = "";
                    txtNum.Text = "";
                    txtSN.Text = "";
                    clearall();
                }
            }
            catch
            {
                txtBillNo.Focus();
                txtBillNo.Text = "";
                txtBoxCode.Text = "";
                lab_StorageSN.Text = "";
                lblRow.Text = "";
                txtNum.Text = "";
                txtSN.Text = "";
                clearall();
            }

        }

        private void txtBoxCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                try
                {
                    DataTable dtOverUn = Bll_RMOut.GetOutDetailOverInfo(BillNo, txtBoxCode.Text);
                    if (dtOverUn != null && dtOverUn.Rows.Count > 0)
                    {
                        MessageBox.Show("该条码已出库,请重新扫码!");
                        txtBoxCode.Text = "";
                        txtBoxCode.Focus();
                        return;
                    }
                    DataTable saaInfo = Bll_RMOut.GetSaaInfo(txtBoxCode.Text);
                    bool isSpe = true;
                    if (saaInfo != null && saaInfo.Rows.Count > 0)
                    {
                        DataRow drsaa = saaInfo.Rows[0];
                        productNumber = drsaa["PartNumber"].ToString();
                        CustomerSN = drsaa["SupplierID"].ToString();
                        ExpiryDate = Convert.ToDateTime(drsaa["ExpirationDate"].ToString());
                        dataCode = drsaa["DateCode"].ToString();
                        if (dataCode.Length > 8)
                        {
                            dataCode = dataCode.Substring(0, 8);
                        }
                        Qty = Convert.ToDecimal(drsaa["Qty"]);
                        lotNo = drsaa["Batch1"].ToString();
                    }
                    else
                    {
                        var CodeArray = txtBoxCode.Text.Split(',');
                        if (CodeArray != null && CodeArray.Length == 8)
                        {
                            //productNumber = CodeArray[2].Substring(0, CodeArray[2].LastIndexOf('-'));
                            productNumber = CodeArray[2];
                            CustomerSN = CodeArray[7];
                            ExpiryDate = Convert.ToDateTime(CodeArray[4].Substring(0, 4) + "-" + CodeArray[4].Substring(4, 2) + "-" + CodeArray[4].Substring(6, 2));
                            dataCode = CodeArray[3].Substring(0, 8);
                            Qty = Convert.ToDecimal(CodeArray[5]);
                            lotNo = CodeArray[6].ToString();
                        }
                        else
                        {
                            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;

                            DialogResult dr = MessageBox.Show("非法标签，如非特殊物料请不要使用！", "出库确认", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);

                            if (dr == DialogResult.OK)
                            {
                                txtBoxCode.Text = "";
                                txtBoxCode.Focus();
                                return;
                            }
                            isSpe = false;
                            productNumber = DtRMOut.Rows[0]["PartNumber"].ToString();
                            CustomerSN = "X";
                            ExpiryDate = Convert.ToDateTime("2999-12-31");
                            dataCode = DateTime.Now.ToString("yyyyMMdd");
                            lotNo = "X";
                            //MessageBox.Show("请选择正确的条码!");
                            //txtBoxCode.Text = "";
                            //txtBoxCode.Focus();
                            //return;
                        }
                    }

                    if (ExpiryDate != null && isSpe)    //判断有效期
                    {
                        //if (DateTime.Now > ExpiryDate)
                        //{
                        //    MessageBox.Show("该物料有效期:" + Convert.ToDateTime(ExpiryDate).ToShortDateString() + "已过，无法出库!");
                        //    txtBoxCode.Text = "";
                        //    txtBoxCode.Focus();
                        //    return;
                        //}
                    }

                    if (!(productNumber.Trim().Contains(DtRMOut.Rows[0]["PartNumber"].ToString().Trim())))
                    {
                        MessageBox.Show("订单物料号与条码物料号不一致!");
                        txtBoxCode.Text = "";
                        txtBoxCode.Focus();
                        return;
                    }
                    else
                    {
                        productNumber = DtRMOut.Rows[0]["PartNumber"].ToString();
                    }

                    var dtInver = Bll_RMOut.getInventoryBySN(realLocationSN, productNumber);
                    if (dtInver != null && dtInver.Rows.Count > 0)
                    {

                        //if (dataCode != dtInver.Rows[0]["DateCode"].ToString())
                        //{
                        //    MessageBox.Show("库位DateCode与条码DateCode不一致!");
                        //    txtBoxCode.Text = "";
                        //    txtBoxCode.Focus();
                        //    return;
                        //}

                        //if (DtRMOut.Rows[0]["Ext3"].ToString() != dtInver.Rows[0]["Version"].ToString())
                        //{
                        //    MessageBox.Show("库位版本与条码版本不一致!");
                        //    txtBoxCode.Text = "";
                        //    txtBoxCode.Focus();
                        //    return;
                        //}
                    }
                    else
                    {
                        MessageBox.Show("该库位" + txtSN.Text + "无库存");
                        txtBoxCode.Text = "";
                        txtSN.Text = "";
                        txtSN.Focus();
                        return;
                    }


                    txtNum.Text = Qty.ToString();
                    txtNum.Focus();
                }
                catch
                {
                    MessageBox.Show("数据异常！");

                }
            }
        }

        public string GetBillInfoMsg(string billNox)
        {
            try
            {
                var dt = Bll_RMOut.getRMRows(billNox, rowNo);
                var dtdetail = Bll_RMOut.getRMDetails(billNox, rowNo);
                StringBuilder sb = new StringBuilder();
                //var isFinish = false;

                if (dt != null && dt.Rows.Count > 0)
                {
                    int rmDetailOverCount = 0;
                    Decimal realQtyCount = Convert.ToDecimal(0);
                    if (dtdetail != null && dtdetail.Rows.Count > 0)
                    {
                        rmDetailOverCount = dtdetail.Rows.Count;
                        foreach (DataRow drDetail in dtdetail.Rows)
                        {
                            realQtyCount = realQtyCount + Convert.ToDecimal(drDetail["RealQty"]);
                        }
                    }
                    decimal planQtyCount = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        decimal planQty = Convert.ToDecimal(dr["PlanQty"]);
                        decimal realQty = Convert.ToDecimal(dr["RealQty"]);
                        if ((dr["Status"].ToString() == "0") && (realQty >= planQty))
                        {
                            // var resRow= Bll_RMOut.UpdateRMRow(dr["BillNo"].ToString(), dr["RowNo"].ToString());
                            MessageBox.Show("该订单处理数量已满，请在原料管理菜单进行[发货确认]");
                            isRowFinish = true;
                        }
                        planQtyCount = planQty;

                    }

                    sb.AppendLine("\r\n下架次数:" + rmDetailOverCount + "\r\n下架数量:" + realQtyCount + "/" + planQtyCount);


                }



                return sb.ToString();
            }
            catch
            {
                return "";
            }
        }

        private void BtnOver_Click(object sender, EventArgs e)
        {

            txtBillNo.Focus();
            txtBillNo.Text = "";
            txtBoxCode.Text = "";
            lab_StorageSN.Text = "";
            txtNum.Text = "";
            txtSN.Text = "";
            BillNo = "";
            rowNo = 0;
            clearall();
        }



    }
}